<?php

namespace app\admin\controller\crm;

use app\admin\controller\Auth;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use think\App;
use think\Exception;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;
use Throwable;

/**
 * @ControllerAnnotation(title="crm_record")
 */
class Contract extends AdminController
{


    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\CrmContract();
        
    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParamesScop();
            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();

            //查询所有管理员
            $adminResult = Db::name('admin')->field('admin_id,username,realname')->select();
            $adminList = [];
            foreach ($adminResult as $admin) {
                $adminList[$admin['username']] = $admin;
            }

            foreach ($list as $key => $value) {
                //替换
                $value['pr_user'] = $adminList[$value['pr_user']]['realname'] ?? '';
                $list[$key] = $value;
            }

            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    // 上传合同
    public function dialogue()
    {

        $id = Request::param('id',0,'intval');
        $result = Db::table('crm_customer')
            ->where(['id'=>$id])
            ->find();
        if (empty($result)){
            $this->error('不存在的客户信息！');

        }

        $contract= Db::table('crm_contract')->alias('r')->field('r.*,a.avatar')->join('admin a','r.admin_id = a.admin_id')->where(['r.customer_id'=>$id])->order('id DESC')->limit(5)->select()->toArray();
        if($contract){
            array_multisort(array_column($contract,'id'),SORT_ASC,$contract);
            $result['contract']=$contract;
        }else{
            $result['contract']=[];
        }

        /*foreach ($result['comment'] as $k => $v){
            $result['comment'][$k]['reply'] = Db::table('crm_reply')->where(['comment_id'=>$v['id']])->select();
        }*/
        // 是否有查看手机号的权限
        if ($this->admin['isphone'] == 0) {
            $result['phone'] = mb_substr($result['phone'], 0, 3).'****'. mb_substr($result['phone'], 7, 11);
        }
        $fields = Db::query('SELECT `editinput` FROM `system_field` WHERE (`edit`=1 AND `table`="crm_customer" AND `editinput` is not null) OR `field`="pr_user" OR `field`="at_user" OR `field`="last_up_time" OR `field`="last_up_records" OR `field`="at_user" OR `field`="create_time" order BY `sort` ASC,id ASC');
        $fields_str='';
        foreach ($fields as $v){
            $fields_str .= trim($v['editinput']);
        }
        $this->app->view->engine()->layout(false);
        $fields_str = $this->display($fields_str,['row'=>$result]);
        $this->assign('fields_str', $fields_str);
        $this->assign('result',$result);
        $this->app->view->engine()->layout($this->layout);
        return $this->fetch();

    }

    public function add()
    {
        if($this->request->post()){

            $data['customer_id'] = Request::param('customer_id');
            if(empty($data['customer_id'])){
                return json(['code'=>0,'msg'=>'请求参数非法!']);
            }

            $customer_row = Db::table('crm_customer')
                ->field('`name`,`phone`')
                ->where(['id'=>$data['customer_id']])
                ->find();
            if(empty($customer_row)){
                return json(['code'=>0,'msg'=>'不存在的客户!']);
            }

            $data['admin_id'] = $this->admin['admin_id'];
            $data['khname'] = $customer_row['name'];
            $data['khphone'] = $customer_row['phone'];
            $data['pr_user'] = $this->admin['username'];
            $data['content'] = Request::param('content');
            $data['pact_files'] = Request::param('pact_files');
            $data['create_time'] = time();

            # 更新合同
            Db::startTrans();
            try{

                # 新增合同记录
                $result = Db::table('crm_contract')
                    ->insert($data);
                if(!$result){
                    throw new Exception("新增合同失败");
                }

                Db::commit();
            }catch (Throwable $exception){
                Db::rollback();
                return json(['code'=>0,'msg'=>$exception->getMessage()]);
            }

            $data['create_time'] = date("Y年m月d日 H:i",$data['create_time']);
            return json(['code'=> 1,'msg'=>'新增合同成功！','data'=>$data]);


//            Db::table('crm_customer')->where(['id'=>$data['customer_id']])->update($genjin);
//
//            $result = Db::table('crm_record')->insert($data);
//            $data['create_time'] = date("Y年m月d日 H:i",$data['create_time']);
//
//            if ($result){
//                return json(['code'=> 1,'msg'=>'跟进记录成功！','data'=>$data]);
//            }else{
//                return json(['code'=>0,'msg'=>'跟进记录失败!']);
//            }
        }
    }



    
}